import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:yi_shop/components/coupon/discount.dart';
import 'package:yi_shop/extensions/context.dart';
import 'package:yi_shop/route/index.dart';
import 'package:yi_shop/ui/keep_alive.dart';
import 'package:yi_shop/utils/colors.dart';
import 'package:yi_shop/utils/styles.dart';
import 'package:yi_shop/utils/svg.dart';
import 'package:yi_shop/utils/tools.dart';

class MineCouponListController extends GetxController with GetSingleTickerProviderStateMixin {
  late TabController controller;

  OverlayEntry? _overlayEntry;

  List<String> tabs = ['优惠券', '支付券', '运费券', '理财券', '金条券'];

  RxInt tabIndex = RxInt(-1);

  List<String> tabList = ['未使用', '已使用', '已过期'];

  /// 显示浮层
  void showOverlay(BuildContext context, double height) {
    hideOverlay();

    /// 防止重复创建，不然失去句柄的OverlayEntry将无法消除
    if (_overlayEntry == null) {
      _overlayEntry = createOverlayEntry(height);
      if (_overlayEntry != null) {
        Overlay.of(context).insert(_overlayEntry!);
      }
    }
  }

  /// 创建浮层
  OverlayEntry createOverlayEntry(double height) {
    return OverlayEntry(
      builder: (BuildContext context) {
        return GestureDetector(
          onTap: hideOverlay,
          child: Transform.translate(
              offset: Offset(0, height),
              child: Material(
                  color: Colors.black26,
                  child: Column(
                    children: [
                      Container(
                        decoration: const BoxDecoration(color: Colors.white),
                        padding: const EdgeInsets.symmetric(vertical: 15, horizontal: 10),
                        alignment: Alignment.topLeft,
                        child: Obx(() => Wrap(
                              spacing: 10,
                              runSpacing: 15,
                              children: tabs
                                  .asMap()
                                  .map((key, value) => MapEntry(
                                      key,
                                      TextButton(
                                        onPressed: () {
                                          tabIndex.value = key;
                                          hideOverlay();
                                        },
                                        style: ButtonStyle(
                                            fixedSize:
                                                const MaterialStatePropertyAll(Size(100, 30)),
                                            backgroundColor:
                                                MaterialStatePropertyAll(activeColor(key)),
                                            alignment: Alignment.center,
                                            shape: MaterialStatePropertyAll(
                                              RoundedRectangleBorder(
                                                  borderRadius: BorderRadius.circular(5.r)),
                                            )),
                                        child: Text(
                                          value,
                                          style: activeStyle(key),
                                        ),
                                      )))
                                  .values
                                  .toList(),
                            )),
                      )
                    ],
                  ))),
        );
      },
    );
  }

  TextStyle activeStyle(int index) {
    if (tabIndex.value == index) {
      return StylesUtils.customTextStyle(
        fontSize: StylesUtils.fontSize13,
      );
    }
    return StylesUtils.customTextStyle(
        fontSize: StylesUtils.fontSize13, color: ColorsUtils.color6666);
  }

  Color activeColor(int index) {
    if (tabIndex.value == index) {
      return ColorsUtils.parseColorFromHexString(ColorsUtils.colorF048);
    }
    return ColorsUtils.parseColorFromHexString(ColorsUtils.colorF2f2);
  }

  /// 隐藏浮层
  void hideOverlay() {
    /// 防止null调用异常
    if (_overlayEntry != null) {
      _overlayEntry?.remove();
      _overlayEntry = null;
    }
  }

  @override
  void onInit() {
    controller = TabController(length: tabList.length, vsync: this);
    super.onInit();
  }

  @override
  void onClose() {
    hideOverlay();
    super.onClose();
  }
}

class MineCouponListPage extends GetView<MineCouponListController> {
  const MineCouponListPage({super.key});

  @override
  Widget build(BuildContext context) {
    GlobalKey topKey = GlobalKey();
    return Scaffold(
      appBar: AppBar(
        key: topKey,
        leading: ToolsUtils.builderLeading(),
        title: TextButton(
            onPressed: () {
              Size size = topKey.size ?? Size.zero;
              controller.showOverlay(context, size.height);
            },
            child: Text.rich(TextSpan(children: [
              TextSpan(
                  text: '优惠券 ',
                  style: StylesUtils.customTextStyle(
                      fontSize: StylesUtils.fontSize18, fontWeight: FontWeight.w700)),
              WidgetSpan(
                  child: SvgUtils.assetName('u15581', width: 12, height: 7),
                  alignment: PlaceholderAlignment.middle)
            ]))),
        actions: [
          IconButton(
              onPressed: () {
                Get.toNamed(RoutePath.couponExplain);
              },
              icon: SvgUtils.assetName('u6107', width: 20, height: 20))
        ],
      ),
      body: buildNestedScrollView(context),
    );
  }

  NestedScrollView buildNestedScrollView(BuildContext context) {
    return NestedScrollView(
      headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
        return [
          SliverPersistentHeader(
            pinned: true,
            delegate: _MyHeader(
                child: Container(
              height: 40,
              alignment: Alignment.centerLeft,
              decoration:
                  BoxDecoration(color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF2f2)),
              child: ToolsUtils.getClientTabBar(controller.tabList, controller.controller,
                  isScrollable: false, indicatorSize: TabBarIndicatorSize.label),
            )),
          )
        ];
      },
      body: TabBarView(
        controller: controller.controller,
        children: [
          KeepAliveWrapperTabView(
            child: const UnusedDiscountView(),
            callback: () {
              Get.put(UnusedDiscountController());
            },
          ),
          KeepAliveWrapperTabView(
            child: const UsedDiscountView(),
            callback: () {
              Get.put(UsedDiscountController());
            },
          ),
          KeepAliveWrapperTabView(
              child: const ExpiredDiscountView(),
              callback: () {
                Get.put(ExpiredDiscountController());
              })
        ],
      ),
    );
  }
}

class _MyHeader extends SliverPersistentHeaderDelegate {
  final Widget child;
  final double height;

  _MyHeader({required this.child, this.height = 40});

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    return child;
  }

  @override
  double get maxExtent => height;

  @override
  double get minExtent => height;

  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) {
    return this != oldDelegate;
  }
}
